package com.example.work.controller;

import com.example.work.entity.Buy;
import com.example.work.entity.Submit;
import com.example.work.entity.UserEntity;
import com.example.work.service.SubmitService;
import com.example.work.service.UserService;
import com.example.work.util.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description: 批量处理
 * @author: JinMu
 * @create: 2018-07-31 10:37
 * @Version: 1.0
 **/
@Controller
public class BuyController {

    private Logger logger = Logger.getLogger(BuyController.class);
    private static final String TargetAccountType = "";//充值账户类型
    private static final String TargetAccountTypeName = "";//充值账户类型名称
    private static final String RechargeMode = "";//充值方式
    private static final String RechargeModeName = "";//充值方式名称
    private static final String Game = "";//充值游戏
    private static final String GameName = "";//充值游戏名称
    private static final String Area = "";//游戏区域
    private static final String AreaName = "";//游戏区域名称
    private static final String Server = "";//游戏服务器
    private static final String ServerName = "";//游戏服务器名称
    private static final String CustomerIP = "";//客户IP/客户区域，用来确定消费区域，只需传一个即可。如果都传以IP为准，如果都不传则默认区域为全国。
    private static final String CustomerRegion = "";
    private static final String ResponseUrl = "";//接收异步通知订单状态的Url
    private static final String Url = "http://www.pvm.com.cn/Api/Pay";//请求地址
    @Autowired
    private UserService userService;
    @Autowired
    private SubmitService submitService;
    private String resu;

    @PostMapping(value = "/buy")
    public String test1(@RequestParam("file") MultipartFile file, @ModelAttribute Buy buy, ModelMap modelmap) {
        UserEntity userEntity = userService.queryuser(buy.getName());
        Vector<Submit> vector = new Vector<>();
        ExecutorService pool = Executors.newCachedThreadPool();
        long startTime = System.currentTimeMillis();
        //文件读取
        try {
            byte[] bytes = file.getBytes();
            String[] str1 = new String(bytes).replaceAll("\r|\n", "").split(",");
            ArrayList<String> str2 = new ArrayList<String>();
            ArrayList<String> str3 = new ArrayList<String>();
            for (String st : str1) {
                if (CheckQQ.check(st)) {
                    str2.add(st);
                } else {
                    str3.add(st);
                }
            }
            logger.info("True QQ" + str2.size() + "----is----" + str2);
            logger.info("False QQ"+ str3.size() + "----is----" + str3);
            //提交线程
            for (int i = 0; i < str2.size(); i++) {
                int j = i;
                pool.execute(new Runnable() {
                    @Override
                    public void run() {
                        Map<String, Object> map = new HashMap<String, Object>();
                        String MerchantOrderID = DateUtil.date2Str(new Date(), "YYYYMMddHHmmss") + System.nanoTime();
                        System.out.println(MerchantOrderID);
                        map.put("MerchantID", userEntity.getMerchantID());
                        map.put("MerchantOrderID", MerchantOrderID);
                        map.put("ProductID", buy.getProductID());
                        map.put("BuyAmount", buy.getBuyAmount());
                        map.put("TargetAccount", str2.get(j));
                        map.put("TargetAccountType", TargetAccountType);
                        map.put("TargetAccountTypeName", TargetAccountTypeName);
                        map.put("RechargeMode", RechargeMode);
                        map.put("RechargeModeName", RechargeModeName);
                        map.put("Game", Game);
                        map.put("GameName", GameName);
                        map.put("Area", Area);
                        map.put("AreaName", AreaName);
                        map.put("Server", Server);
                        map.put("ServerName", ServerName);
                        map.put("CustomerIP", CustomerIP);
                        map.put("CustomerRegion", CustomerRegion);
                        map.put("ResponseUrl", ResponseUrl);
                        map.put("Sign", MD5Util.getmd32(userEntity.getMerchantID() + MerchantOrderID + buy.getProductID() + buy.getBuyAmount() + str2.get(j) + userEntity.getKey()));
                       /* String result = HttpUtil.doPost(Url, map);
                        System.out.println(result);
                        String state = ResultUtil.getstate(result.replaceAll("<cards />", ""));
                        Submit submit = new Submit(MerchantOrderID, str2.get(j), userEntity.getMerchantID(), buy.getBuyAmount(), state, DateUtil.date2Str(new Date(), "yyyy-MM-dd HH:mm:ss"));*/
                        Submit submit = new Submit(MerchantOrderID,str2.get(j),userEntity.getMerchantID(),buy.getBuyAmount(), "1", DateUtil.date2Str(new Date(), "yyyy-MM-dd HH:mm:ss"));
                        submitService.addsubmit(submit);
                        vector.add(submit);
                    }
                });

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            Thread.sleep(500);
            modelmap.addAttribute("arrayList", vector);
            System.out.println("vector is " + vector);
            long endTime = System.currentTimeMillis();
            System.out.println("this app runtime：" + (endTime - startTime) + "ms");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       return "buy";
    }

    @PostMapping("/buy_s")
    public String test(@ModelAttribute Buy buy, ModelMap modelmap){
        ArrayList<Submit> arrayList = new ArrayList<>();
        String MerchantOrderID = "1000"+ DateUtil.date2Str(new Date(),"yyyyMMddHHmmssmmddss");
        UserEntity userEntity = userService.queryuser(buy.getName());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("MerchantID", userEntity.getMerchantID());
        map.put("MerchantOrderID",MerchantOrderID );
        map.put("ProductID", buy.getProductID());
        map.put("BuyAmount", buy.getBuyAmount());
        map.put("TargetAccount", buy.getTargetAccount());
        map.put("TargetAccountType", TargetAccountType);
        map.put("TargetAccountTypeName", TargetAccountTypeName);
        map.put("RechargeMode", RechargeMode);
        map.put("RechargeModeName", RechargeModeName);
        map.put("Game", Game);
        map.put("GameName", GameName);
        map.put("Area", Area);
        map.put("AreaName", AreaName);
        map.put("Server", Server);
        map.put("ServerName", ServerName);
        map.put("CustomerIP", CustomerIP);
        map.put("CustomerRegion", CustomerRegion);
        map.put("ResponseUrl", ResponseUrl);
        map.put("Sign", MD5Util.getmd32(userEntity.getMerchantID() + MerchantOrderID + buy.getProductID() + buy.getBuyAmount() + buy.getTargetAccount() + userEntity.getKey()));
        String result = HttpUtil.doPost(Url, map);
        System.out.println(result);
        String state = ResultUtil.getstate(result.replaceAll("<cards />", ""));
        Submit submit = new Submit(MerchantOrderID, buy.getTargetAccount(), userEntity.getMerchantID(), buy.getBuyAmount(), state, DateUtil.date2Str(new Date(), "yyyy-MM-dd HH:mm:ss"));
        arrayList.add(submit);
        modelmap.addAttribute("arrayList", arrayList);
        return "buy_s";
    }
}
